<template>
    <!-- 搜索相关 start -->
    <el-form :model="queryParams" ref="refForm" size="default" :inline="true" v-show="showSearch" label-width="38px">
        <el-form-item label="人员" prop="user" label-width="50px">
            <el-select v-model="queryParams.userId" placeholder="请选择人员" clearable style="width: 120px">
                <el-option v-for="(item, index) in userOptions" :key="index" :label="item.name"
                    :value="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="记忆开始日期" prop="rememberStartDate" label-width="98px">
            <el-date-picker v-model="queryParams.rememberStartDate" placeholder="请选择记忆开始日期" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" :style="{ width: '100%' }" clearable>
            </el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="title" label-width="50px">
            <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleGetList" />
        </el-form-item>
        <el-form-item label="任务类别" prop="taskType" label-width="68px">
            <el-select v-model="queryParams.taskType" placeholder="请选择任务类别" clearable style="width: 150px">
                <el-option v-for="(item, index) in taskTypeOptions" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="default" @click="handleGetList">搜索</el-button>
            <el-button type="primary" icon="el-icon-refresh" size="default" @click="resetForm(refForm)">重置</el-button>
        </el-form-item>
    </el-form>
    <!-- 搜索相关 end -->

    <!-- 操作相关 start -->
    <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="default"
                @click="outerVisible = true">新增</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="default" @click="handleUpdate"
                :disabled="true">修改</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="default" @click="handleDeleteConfirmEvent"
                :disabled="true">删除</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="default" :disabled="true">导出</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-s-operation" size="default" :disabled="true">日志</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-switch v-model="addFormData.autoCreateTask" class="ml-2" inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="自动生成任务"
                inactive-text="不自动生成任务" />
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="handleGetList"></right-toolbar> -->
    </el-row>
    <!-- 操作相关 end -->

    <!-- 表格相关 start -->
    <el-table :data="filterTableData" style="height: 550px;">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="55" :index="indexMethod" />
        <el-table-column label="人员" prop="userName" width="70" />
        <el-table-column label="标题" prop="title" width="120" show-overflow-tooltip />
        <el-table-column label="内容" prop="content" width="120" show-overflow-tooltip />
        <el-table-column label="任务类别" prop="taskType" width="80" />
        <el-table-column label="备注" prop="remark" width="100" show-overflow-tooltip />
        <el-table-column label="是否已生成任务" width="100" show-overflow-tooltip>
            <template #default="scope">
                <el-button :type="getCreatedTaskType(scope.row.createdTask)" size="default" :disabled="true">
                    {{ scope.row.createdTask ? '是' : '否' }}</el-button>
            </template>
        </el-table-column>
        <el-table-column width="160">
            <template #header>
                <el-input v-model="search" size="default" placeholder="Type to search" />
            </template>
            <template #default="scope">
                <el-button type="primary" v-if="!scope.row.createdTask"
                    @click="handleCreateTask(scope.$index, scope.row)">创建任务</el-button>
                <el-button type="primary" :icon="Edit" @click="handleEdit(scope.$index, scope.row)" />
                <!-- <template #default="scope"> -->
                <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
                    icon-color="#626AEF" title="确定完成删除此计划么？" @confirm="handleDeleteConfirmEvent(scope.$index, scope.row)">
                    <template #reference>
                        <el-button type="primary" :icon="Delete" />
                    </template>
                </el-popconfirm>
                <!-- </template> -->
            </template>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total=pageData.totalNum @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top: 20px;" />
    <!-- 表格相关 end -->

    <!-- 添加或修改计划对话框 start-->
    <el-dialog :title="title" width="500px" append-to-body draggable v-model="outerVisible">
        <el-row :gutter="15">
            <el-form :model="addFormData" :rules="rules" :size="formSize" label-width="150px" ref="addFormRef"
                style="max-width: 600px">
                <el-col :span="24">
                    <el-form-item label="人员" prop="userId">
                        <el-select v-model="addFormData.userId" placeholder="请输入人员" clearable
                            :style="{ width: '100%' }">
                            <el-option v-for="(item, index) in userOptions" :key="index" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="addFormData.title" placeholder="请输入标题" clearable :style="{ width: '100%' }">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="内容" prop="content">
                        <el-input v-model="addFormData.content" type="textarea" placeholder="请输入内容" clearable
                            :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="任务类别" prop="taskType">
                        <el-select v-model="addFormData.taskType" placeholder="请选择任务类别" clearable
                            :style="{ width: '100%' }">
                            <el-option v-for="(item, index) in taskTypeOptions" :key="index" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="addFormData.taskType == 0">
                    <el-form-item label="记忆任务开始日期" prop="rememberStartDate">
                        <el-date-picker v-model="addFormData.rememberStartDate" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" :style="{ width: '100%' }" placeholder="请选择日期"
                            clearable></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="addFormData.taskType == 1">
                    <el-form-item label="定时任务时间选择" prop="scheduledTaskDateTime">
                        <el-date-picker v-model="addFormData.scheduledTaskDateTime" format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss" type="datetime" :style="{ width: '100%' }"
                            placeholder="请选择定时任务时间" clearable></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="addFormData.taskType == 1">
                    <el-form-item label="提前几分钟" prop="aheadMinutes">
                        <el-slider :max='100' :step='1' v-model="addFormData.aheadMinutes"></el-slider>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="addFormData.remark" type="textarea" placeholder="请输入备注"
                            :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item size="large">
                        <el-button type="primary" @click="submitAddForm(addFormRef)">保存</el-button>
                        <el-button @click="outerVisible = false">取消</el-button>
                        <el-button @click="resetForm(addFormRef)">重置</el-button>
                    </el-form-item>
                </el-col>
            </el-form>
        </el-row>
        <!-- 也可以用这种方式，看起来按钮更好看些，但是默认不居中，需要调下。 -->
        <!-- <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div> -->
    </el-dialog>
    <!-- 添加或修改计划对话框 end -->
</template>
<script lang="ts" setup>
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { showErrorMsg, showSuccessMsg, resetForm, getNowDate, indexMethod } from '@/api/common';
import { getUserInfo } from "@/utils/auth";
import type { FormInstance, FormRules, ComponentSize } from 'element-plus'
import { Delete, Edit, InfoFilled } from '@element-plus/icons-vue'
import { page, add, delPlan, createTask } from "@/api/dailyPlan/dailyPlan";
import { listAll } from "@/api/user/user";
import type { DailyPlan, DailyPlanAddRequest, QueryParams } from '@/api/dailyPlan/dailyPlan';
import type { ApiResponse, PageResponse, OnlyIdRequest, PageData } from '@/api/common';
import type { User } from '@/api/user/user'; 
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let title = ref('新增计划')
let outerVisible = ref(false)
// 显示搜索条件
let showSearch = ref<boolean>(true)
const refForm = ref<FormInstance>()
let onlyIdRequest = reactive<OnlyIdRequest>({
    id: null,
})
let pageData = reactive<PageData<DailyPlan>>({
    totalNum: 0,
    tableData: [],
})
let queryParams = reactive<QueryParams>({
    pageNum: 1,
    pageSize: 10,
    userId: null,
    rememberStartDate: '',
    title: '',
    taskType: '',
})
let taskTypeOptions = ref(
    [{
        "label": "记忆任务",
        "value": 0
    }, {
        "label": "定时任务",
        "value": 1
    }],
)
let userOptions = reactive<User[]>([]);
const search = ref('')
const filterTableData = computed(() =>
    pageData.tableData.filter(
        (data) =>
            !search.value ||
            data.title.toLowerCase().includes(search.value.toLowerCase()) ||
            data.content.toLowerCase().includes(search.value.toLowerCase())
    )
)
const handleEdit = (index: number, row: DailyPlan) => {
    console.log(index, row.id)
}
const handleDeleteConfirmEvent = (index: number, row: DailyPlan) => {
    onlyIdRequest.id = row.id;
    delPlan(onlyIdRequest).then((res: ApiResponse<string>) => {
        // console.log(res);
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("删除成功")
            handleGetList();
        }
    });
    // console.log(index, row.id)
}
const handleSizeChange = (newSize: number) => {
    queryParams.pageSize = newSize;
    handleGetList();
}
const handleCurrentChange = (newPage: number) => {
    queryParams.pageNum = newPage;
    handleGetList();
}
const handleUpdate = (row: DailyPlan) => {}
const handleGetList = () => {
    page(queryParams).then((res: ApiResponse<PageResponse<DailyPlan>>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            let totalTemp = parseInt(res.data.total);
            pageData.totalNum = totalTemp;
            pageData.tableData = res.data.records;
        }
    });
}
onMounted(() => {
    // 查询所有人员
    listAll().then((res: ApiResponse<User[]>) => {
        // 这种直接赋值的方式，会破坏Vue 的响应式系统
        // userOptions = response.data
        // 使用数组的 push 方法来更新 userOptions
        // userOptions.splice(0, userOptions.length, ...response.data);
        // 这两种方式都可以。
        let userList = res.data;
        userOptions.push(...userList);
        if (userList.length == 1) {
            queryParams.userId = userList[0].id;
            addFormData.userId = userList[0].id;
        }
    })
})
const addFormRef = ref<FormInstance>()
const formSize = ref<ComponentSize>('default')
let addFormData = reactive<DailyPlanAddRequest>({
    userId: null,
    userName: '',
    rememberStartDate: getNowDate(),
    title: '',
    content: '',
    taskType: 0,
    scheduledTaskDateTime: '',
    aheadMinutes: 5,
    remark: '',
    autoCreateTask: true,
})
// 初始表单规则
let rules = ref<FormRules<DailyPlanAddRequest>>({
    userId: [{
        required: true,
        message: '请选择人员',
        trigger: 'change'
    }],
    title: [{
        required: true,
        message: '请输入标题',
        trigger: 'blur'
    }],
    content: [{
        required: true,
        message: '请输入内容',
        trigger: 'blur'
    }],
    taskType: [{
        required: true,
        message: '请选择任务类别',
        trigger: 'change'
    }],
    rememberStartDate: [{
        required: true,
        message: '请选择记忆开始日期',
        trigger: 'change'
    }],
    scheduledTaskDateTime: [{
        required: false,
        message: '请选择定时时间',
        trigger: 'change'
    }],
    remark: []
});
watch(() => addFormData.taskType, (newValue) => {
    if (newValue === 0) {
        rules.value.rememberStartDate = [];
        rules.value.rememberStartDate.push({
            required: true,
            message: '请选择记忆开始日期',
            trigger: ['change', 'blur']
        })
        rules.value.scheduledTaskDateTime = [];
        rules.value.scheduledTaskDateTime.push({
            required: false,
            message: '请选择定时时间',
            trigger: ['change', 'blur']
        })
    } else if (newValue === 1) {
        rules.value.rememberStartDate = [];
        rules.value.rememberStartDate.push({
            required: false,
            message: '请选择记忆开始日期',
            trigger: ['change', 'blur']
        })
        rules.value.scheduledTaskDateTime = [];
        rules.value.scheduledTaskDateTime.push({
            required: true,
            message: '请选择定时时间',
            trigger: ['change', 'blur']
        })
    }
});
const submitAddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            add(addFormData).then((res: ApiResponse<string>) => {
                if (res.status != 200) {
                    showErrorMsg(res.msg);
                } else {
                    showSuccessMsg("新增成功");
                    outerVisible.value = false;
                    handleGetList();
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCreateTask = (index: number, row: DailyPlan) => {
    onlyIdRequest.id = row.id;
    createTask(onlyIdRequest).then((res: ApiResponse<string>) => {
        if (res.status != 200) {
            showErrorMsg(res.msg);
        } else {
            showSuccessMsg("创建成功")
            handleGetList();
        }
    });
}
const getCreatedTaskType = (createdTask: boolean) => {
    if (createdTask) {
        return 'success';
    }
    return 'warning';
}
onMounted(()=>{
    const userInfo = getUserInfo();
    queryParams.userId = userInfo.id;
    addFormData.userId = userInfo.id;
})
</script>
<style></style>